package com.imooc.network;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/** UDP只管发的网络编程
 * @Date:2021/10/21/20:08
 * @Description:
 */
public class UDPTest {

    @Test
    public void test01() throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String str = "我是UDP方式发送的捣蛋";
        byte[] data = str.getBytes();

        InetAddress localhost = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, localhost, 9090);

        socket.send(packet);

        socket.close();


    }


    @Test
    public void test02() throws IOException {
        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(datagramPacket);

        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength() ));
        socket.close();

    }


}
